import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class MyNotification {
  int id = 0;
  late Function needDo;

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
  FlutterLocalNotificationsPlugin();



  MyNotification() {
    initializeNotifications();
    flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<
        AndroidFlutterLocalNotificationsPlugin>()?.requestPermission();
  }


  Future<void> initializeNotifications() async {

    const AndroidInitializationSettings initializationSettingsAndroid =
    AndroidInitializationSettings('splash');
    final DarwinInitializationSettings initializationSettingsDarwin =
    DarwinInitializationSettings(
        onDidReceiveLocalNotification: onDidReceiveLocalNotification);
    final LinuxInitializationSettings initializationSettingsLinux =
    LinuxInitializationSettings(defaultActionName: 'Open notification');
    final InitializationSettings initializationSettings = InitializationSettings(
        android: initializationSettingsAndroid,
        iOS: initializationSettingsDarwin,
        linux: initializationSettingsLinux);
    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onDidReceiveNotificationResponse: onDidReceiveNotificationResponse);
  }

  Future<void> showNotification(String title, String msg, String payload, Function d) async {
    needDo = d;
    const AndroidNotificationDetails androidNotificationDetails =
    AndroidNotificationDetails('your channel id', '聊天室通知',
        channelDescription: '各项通知的设定',
        importance: Importance.max,
        priority: Priority.high,
        ticker: 'ticker');
    const NotificationDetails notificationDetails =
    NotificationDetails(android: androidNotificationDetails);

    await flutterLocalNotificationsPlugin.show(
        id++, title, msg, notificationDetails,
        payload: payload);
  }

  Future<void> onDidReceiveNotificationResponse(
      NotificationResponse response) async {
    // Handle the notification response here
    // You can navigate to a specific page or perform a specific action
    print('Notification tapped: ${response.payload}');
    needDo(); // 调用 needDo 函数，其中执行你需要的操作
  }

  Future<void> onDidReceiveLocalNotification(
      int id, String? title, String? body, String? payload) async {
    // Display a dialog or perform an action on local notification received
    // You can navigate to a specific page or perform a specific action
    print('Received local notification: $title - $body');
  }
}
